#include "lua.h"
#include "lauxlib.h"
#include "cm_pm.h"
#include "cm_sys.h"
#include "cm_os.h"
#include "lua_scheduler.h"

// Lua: mcu.reboot()
static int l_mcu_reboot(lua_State *L) {
    cm_pm_reboot();
    return 0; // This function will not return
}

// Lua: mcu.chip_id() -> string
static int l_mcu_chip_id(lua_State *L) {
    // Assuming cm_sys_get_chip_id exists and returns a string.
    // We may need to find the correct function in the SDK.
    // For now, let's use a placeholder if we can't find the exact function.
    // After searching, let's assume there isn't a direct chip_id function,
    // but we can return the IMEI as a unique identifier for now.
    char imei[32] = {0};
    cm_sys_get_imei(imei);
    lua_pushstring(L, imei);
    return 1;
}

// Lua: mcu.sleep(ms)
static int l_mcu_sleep(lua_State *L) {
    int ms = luaL_checkinteger(L, 1);
    if (ms <= 0) {
        // Yield for one scheduler tick to allow other tasks to run
        return lua_yield(L, 0);
    }

    lua_task_t *current_task = lua_scheduler_get_current_task();
    if (current_task) {
        uint32_t ticks_to_sleep = (uint32_t)((((uint64_t)ms) * osKernelGetTickFreq()) / 1000);
        current_task->wakeup_time = osKernelGetTickCount() + ticks_to_sleep;
        return lua_yield(L, 0); // Yield control back to the scheduler
    } else {
        // Fallback to blocking sleep if not running in a scheduled task
        osDelay((uint32_t)((((uint64_t)ms) * osKernelGetTickFreq()) / 1000));
    }

    return 0;
}


static const luaL_Reg mcu_lib[] = {
    {"reboot", l_mcu_reboot},
    {"chip_id", l_mcu_chip_id},
    {"sleep", l_mcu_sleep},
    {NULL, NULL}
};

int luaopen_mcu(lua_State *L) {
    luaL_newlib(L, mcu_lib);
    return 1;
}
